package com.cskaoyan.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author stone
 * @date 2022/11/10 21:09
 */
public class CommonUtil {

    public static Set<Class> getClasses(String packageName) {
        Set<Class> classes = new HashSet<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        Enumeration<URL> resources = null;
        packageName = packageName.replace(".", "/");
        try {
            resources = classLoader.getResources(packageName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            String protocol = url.getProtocol();
            if ("file".equals(protocol)) {
                String filePath = null;
                try {
                    filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                    getClasses(classes, packageName, filePath);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return classes;


    }
    private static void getClasses(Set<Class> classes, String packageName, String filePath) throws ClassNotFoundException {
        File file = new File(filePath);
        String[] list = file.list();
        packageName = packageName.replaceAll("/", ".");
        for (int i = 0; i < list.length; i++) {
            String item = list[i];
            if (!item.endsWith(".class")) {
                getClasses(classes,(packageName + "." + item),(filePath + File.separator + item));
                continue;
            }
            item = item.substring(0, item.length() - 6);
            String allClassName = packageName + "." + item;
            classes.add(Class.forName(allClassName));
        }

    }
}
